package social.hub.impl.jersey.api;

import static social.hub.api.google.orkut.OrkutConstants.*;

import java.util.List;

import javax.ws.rs.core.MediaType;

import social.hub.api.ApiConfig;
import social.hub.api.google.orkut.OrkutActivity;
import social.hub.api.google.orkut.OrkutApi;
import social.hub.api.google.orkut.OrkutProfile;
import social.hub.api.google.orkut.util.OrkutFriendsListResponse;
import social.hub.api.google.orkut.util.OrkutProfileResponse;
import social.hub.api.google.orkut.util.OrkutRPCData;
import social.hub.api.google.orkut.util.OrkutRPCRequest;
import social.hub.impl.jersey.util.ClientFactory;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource.Builder;

public class JerseyOrkutApi implements OrkutApi {

	private final Client client;

	public JerseyOrkutApi(ApiConfig config) {
		client = ClientFactory.createClient(config, OAUTH_SCOPE_FOR_RPC);
	}

	@Override
	public List<OrkutProfile> getFriends() {
		return getFriends(SELF_ID);
	}

	@Override
	public List<OrkutProfile> getFriends(String orkutId) {

		OrkutRPCData data = new OrkutRPCData();
		data.setGroupId(FRIENDS_GROUP);
		data.setUserId(VIEWER_ID);

		OrkutFriendsListResponse response = rpcRequest("people.get", data, ORKUT_BASE_URL, OrkutFriendsListResponse.class);

		return response.getData().getList();

	}

	@Override
	public OrkutProfile getProfile() {
		return getProfile(SELF_ID);
	}

	@Override
	public OrkutProfile getProfile(String orkutId) {

		OrkutRPCData data = new OrkutRPCData();
		data.setGroupId(SELF_GROUP);
		data.setUserId(VIEWER_ID);

		OrkutProfileResponse response = rpcRequest("people.get", data, ORKUT_BASE_URL, OrkutProfileResponse.class);

		return response.getData();

	}

	@Override
	public void updateStatus(String status) {
		updateStatus(status, SELF_ID);
	}

	@Override
	/**
	 * http://www.opensocial.org/Technical-Resources/opensocial-spec-v081/rpc-protocol
	 */
	public void updateStatus(String status, String orkutId) {

		OrkutActivity activity = new OrkutActivity();
		activity.setTitle("Titulo");
		activity.setBody(status);

		OrkutRPCData data = new OrkutRPCData();
		data.setGroupId(SELF_GROUP);
		data.setAppId(SELF_APP);
		data.setUserId(orkutId);

		data.setActivity(activity);

		rpcRequest("activities.create", data, ORKUT_BASE_URL, null);

	}

	private <T> T rpcRequest(String method, OrkutRPCData data, String baseUrl, Class<T> clazz) {

		OrkutRPCRequest rpcData = new OrkutRPCRequest(method, data);

		Builder builder = client.resource(baseUrl).type(MediaType.APPLICATION_JSON_TYPE)
				.accept(MediaType.APPLICATION_JSON_TYPE);

		T response = null;

		if (clazz != null) {
			response = builder.post(clazz, rpcData);
		} else {
			builder.post(rpcData);
		}

		return response;

	}

}
